# -*- coding: utf-8 -*-
from django.shortcuts import render,get_object_or_404, render_to_response
from django.http import HttpResponseRedirect,HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext, loader
from poudres.models import Poudre, Event
from django.utils import simplejson 
import re, json   

# Create your views here.
def autocompletion(request):
    if request.is_ajax():
        q = request.GET.get('term', '')   
        listeP = Poudre.objects.filter(nom__istartswith=q)
        results = []
        for p in listeP:
            tab_rep = {}
            
            tab_rep['id'] = p.id
            tab_rep['label'] = p.nom
            tab_rep['value'] = p.nom
            
            results.append(tab_rep)
        data = simplejson.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

def search_poudre(request): 
    if request.is_ajax():
        q = request.GET.get('term', '')  
        question = re.sub(r'_', " ", q);
        p = get_object_or_404(Poudre,nom__exact=question)
        listeE = p.event_set.all()
        results = []
        for event in listeE:           
            results.append([event.TE.__unicode__(), event.date.strftime('%Y-%m-%d %H:%M:%S'), event.quantite.__str__(),event.prix.__str__(), event.somme.__str__(), event.instock.__str__()])
        data = simplejson.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

def afficher(request):
    context = {'PAGE_TITLE': 'Accueil',
     'WEBSITE_TITLE': 'Tuto Django'}
    return render_to_response('poudres/index1.html',context)
